var express = require('express');
var router = express.Router();
const path = require('path');
const userController = require('../controller/userController');
const {
  returnValueFromToken,
  SuccessData,
  SimpleData,
} = require('../common/returnDataFormat');
const { modifyUser } = require('../controller/adminController');
const multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
    //文件保存路径
  },
  filename: function (req, file, cb) {
    cb(null, new Date().getTime() + '_' + file.originalname);
    //存储文件名
  },
});
const upload = multer({ storage: storage });
// 用户注册路由
router.post('/register', async function (req, res) {
  const result = await userController.addUser(req.body);
  res.send(result);
});

// 用户登录路由
router.post('/login', async function (req, res, next) {
  let result = await userController.userLogin(req.body);
  res.send(result);
});

// 用户修改信息路由
router.post('/modify', async function (req, res) {
  const userId = await returnValueFromToken(
    req.headers.authorization,
    'userId'
  );
  const result = await userController.modifyUser([req.body, userId]);
  res.send(result);
});

//用户注销路由
router.get('/delete', async function (req, res) {
  const userId = await returnValueFromToken(
    req.headers.authorization,
    'userId'
  );
  const result = await userController.deleteUser(userId);
  res.send(result);
});

// 查询用户信息路由
router.get('/userInfo', async function (req, res) {
  const userName = await returnValueFromToken(
    req.headers.authorization,
    'username'
  );
  const result = await userController.selectUserByName(userName);
  res.send(result);
});

router.get('/findOneUser', async (req, res) => {
  const result = await userController.findOneUser(req.query.user_id);
  res.send(result);
});

router.post('/upload', upload.single('file'), async function (req, res, next) {
  let userId = await returnValueFromToken(req.headers.authorization, 'userId');
  const url = '/' + req.file.path.replace(/\\/g, '/');
  const result = await modifyUser([userId, { avatar_url: url }]);
  if (result.code == 200) {
    res.send(SuccessData({ path: url }));
  } else {
    res.send(SimpleData(500, '图片上传失败'));
  }
});

router.post('/pagingUsers', async (req, res) => {
  const { offset = 1, limit, username } = req.body;
  const result = await userController.pagingUsers({ offset, limit, username });
  if (result) {
    res.send(SuccessData(result));
  } else {
    res.send(result);
  }
});
module.exports = router;
